package com.hullbreach.rogue;

import java.util.LinkedList;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.extension.tmx.TMXLayer;
import org.andengine.extension.tmx.TMXProperties;
import org.andengine.extension.tmx.TMXTile;
import org.andengine.extension.tmx.TMXTileProperty;
import org.andengine.extension.tmx.TMXTiledMap;
import org.andengine.util.debug.Debug;

public class Map {

	/* Since this class is a singleton, we must declare an instance
	 * of this class within itself. The singleton will be instantiated
	 * a single time during the course of an application's full life-cycle
	 */
	private static Map INSTANCE;
	private TMXTiledMap mTMXTiledMap;
    private TMXLayer tmxLayer;
    private TMXTile tmxTile;
	
	private LinkedList<GameObject> entities = new LinkedList<GameObject>();
	private TMXTiledMap currentTMXTiledMap;
	
	public static Map getInstance(){
		if(INSTANCE == null){
			INSTANCE = new Map();
		}
		return INSTANCE;
	}
	
	public LinkedList<GameObject> getEntities() {
		return entities;
	}
	public void setEntities(LinkedList<GameObject> entities) {
		this.entities = entities;
	}
	public TMXTiledMap getCurrentTMXTiledMap() {
		return currentTMXTiledMap;
	}
	public void setCurrentTMXTiledMap(TMXTiledMap currentTMXTiledMap) {
		this.currentTMXTiledMap = currentTMXTiledMap;
	}
	
	public int[] getTileXY( float coordX, float coordY )
	{
		int[] coordArray = {0,0};
        TMXLayer tmxLayer = getCurrentTMXTiledMap().getTMXLayers().get(0);
        tmxTile = tmxLayer.getTMXTileAt(coordX,coordY);
        
        if (tmxTile != null)
        {
        	coordArray[0]=tmxTile.getTileX();
        	coordArray[1]=tmxTile.getTileY();
    		return coordArray;
        }
        else
        {
        	return null;
        }
        
	}
	
	public boolean canMoveTo( GameObject player, float coordX, float coordY)
	{
		boolean canMove = false;
				
        TMXLayer tmxLayer = getCurrentTMXTiledMap().getTMXLayers().get(0);
        tmxTile = tmxLayer.getTMXTileAt(coordX,coordY);
        if(tmxTile != null){
        	
        	 final TMXProperties<TMXTileProperty> pTMXTileProperties;
             pTMXTileProperties = tmxTile.getTMXTileProperties(mTMXTiledMap);
             
             if(pTMXTileProperties != null)
             { //Avoid NullPointerException
            	 if(pTMXTileProperties.containsTMXProperty("name", "wall") || pTMXTileProperties.containsTMXProperty("name", "wall2"))
            	 {
            		 //Debug.e("WALL");
            		 return false;
            	 }
            	 else
            	 { //Allow to move over non-property tiles.
                     return true;
            	 }        	
        	
             }
		
        }    

		
		return canMove;
	}
}
